const AdminUser = require('../../models/AdminUser');

module.exports = app => {
  const express = require('express');
  const jwt = require('jsonwebtoken')
  const assert = require('http-assert')
  const router = express.Router({
    mergeParams:true
  });
  // const category = require('../../models/Category')  


  /**
   * 创建分类接口
   */
  router.post('/',async (req, res) => {
    const model = await req.Model.create(req.body)
    res.send(model)
  });

  /**
   * 查找列表接口
   */
    router.get('/',async (req,res,next) => {
      const token = String(req.headers.authorization || '').split(' ').pop()
      assert(token,401,'请先登录')
      const {id} = jwt.verify(token,app.get('secret'))
      assert(id,401,'请先登录')
      req.user = await AdminUser.findById(id)
      assert(req.user,401,'请先登录')

      console.log(req.user);
      await next()
    },async (req, res) => {
      let queryOptions = {}
      if(req.Model.modelName === 'Category') {
        queryOptions.populate = 'parent'
      }
      const items = await req.Model.find().setOptions(queryOptions).limit(100)
      res.send(items)
    });

   /**
    * 获取某一个分类详情页面接口
    */
    router.get('/:id',async (req, res) => {
      const model = await req.Model.findById(req.params.id)
      res.send(model)
    });
      
    /**
     * 查找并更新列表接口
     */
    router.put('/:id',async (req, res) => {
      const items = await req.Model.findByIdAndUpdate(req.params.id,req.body)
      res.send(items)
    });

    /**
     * 列表删除接口
     */
    router.delete('/:id',async (req, res) => {
      const items = await req.Model.findByIdAndDelete(req.params.id,req.body)
      res.send({
        success:true
      })
    });

  //登录效验中间件
  const authMiddleware = require('../../middleware/auth')

  const resourceMiddlewear =  require('../../middleware/resource')
  app.use('/admin/api/rest/:resource',authMiddleware(),resourceMiddlewear(),router);




  // 图片上传接口
  const multer = require('multer')
  const upload = multer({dest:__dirname + '/../../uploads'})
  app.post('/admin/api/upload', upload.single('file') ,(req, res) => {
    const file = req.file
    file.url = `http://localhost:3000/uploads/${file.filename}`
    res.send(file)
  });


  // 登录的路由
  app.post('/admin/api/login',async (req, res) => {
    const { username, password } = req.body
    //1.根据用户名找用户
    const AdminUser = require('../../models/AdminUser')
    const user = await AdminUser.findOne({
      username
    }).select('+password')
    assert(user,422,'用户不存在')
    // if(!user) {
    //   return res.status(422).send({
    //     message:"用户名不存在"
    //   })
    // }
    //2.校验密码
    const isValid = require('bcrypt').compareSync(password,user.password)
    assert(isValid,422,'密码错误')
    // if(!isValid) {
    //   return res.status(422).send({
    //     message:'密码错误'
    //   })
    // }
    //3.返回token
    const token = jwt.sign({id:user._id},app.get('secret'))
    res.send({token}) 
  });



  // 错误处理
  app.use(async (err,req,res,next) => {
    // console.log(err);
    res.status(err.statusCode || 500).send({
      message:err.message
    })
  })

}


